﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AP.Framework.Infrastructure.Repositories.IRepositories;
using AP.Framework.Infrastructure.Entities;
using System.IO;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using AP.Web.Areas.Admin.Models;
using AP.Framework.Utilities.MvcPager;
namespace AP.Web.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        IProduct _product;
        IProductCategory _productCategory;
        public ProductController(IProduct product, IProductCategory productCategory)
        {
            _product = product;
            _productCategory = productCategory;
        }
        public ActionResult Index(int? page)
        {
            var productlList = from t in _product.GetAll()
                               join t1 in _productCategory.GetAll() on t.ProductCategoryId equals t1.ID
                               orderby t.Sequence
                               select new ProductModels
                               {
                                   ID = t.ID,
                                   Name = t.Name,
                                   CategoryName = t1.Name,
                                   Sequence = t.Sequence,
                                   IsDisable = t.IsDisable,
                                   ModifyBy = t.ModifyBy,
                                   ModifyTime = t.ModifyTime
                               };
            return View(productlList.AsQueryable().ToPagedList(page ?? 1, 10));
        }
        public ActionResult Add()
        {
            var proCategoryList = _productCategory.GetAll().OrderBy(p => p.Sequence).Select(p => new SelectListItem() { Value = p.ID.ToString(), Text = p.Name });
            ViewBag.proCategoryList = proCategoryList;
            return View();
        }
        [HttpPost]
        public ActionResult Add(cms_Product model)
        {
            if (ModelState.IsValid)
            {
                model.ModifyBy = "Admin";
                model.ModifyTime = DateTime.Now.Date;
                _product.Add(model);
            }
            return RedirectToAction("Index");
        }
        public ActionResult Edit(int productId)
        {
            var proCategoryList = _productCategory.GetAll().OrderBy(p => p.Sequence).Select(p => new SelectListItem() { Value = p.ID.ToString(), Text = p.Name });
            ViewBag.proCategoryList = proCategoryList;
            cms_Product param = _product.FindById(productId);
            return View(param);
        }
        [HttpPost]
        public ActionResult Edit(cms_Product model)
        {
            if (ModelState.IsValid)
            {
                model.ModifyBy = "Admin";
                model.ModifyTime = DateTime.Now.Date;
                _product.Modify(model);
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int productId)
        {
            cms_Product model = _product.FindById(productId);
            _product.Remove(model);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Andy-Peng
        /// 2012-10-13
        ///文本编辑器上传图片和文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            string result = string.Empty;  // 返回的结果
            string folder = "/Upload/System";// 上传的文件夹
            string errMsg = string.Empty;  // 错误信息
            byte[] file = null;            // 统一转换为byte数组处理
            string fileName = string.Empty;// 选择的文件名
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];//HTML5上传的整个POST数据流就是上传的文件完整数据，而本地文件名等信息储存于HTTP_CONTENT_DISPOSITION这个服务器变量中
            if (!string.IsNullOrWhiteSpace(disposition))
            {
                //HTML5上传 Google与Firefox 浏览器使用这种方式，不然取不到选择的文件名
                file = Request.BinaryRead(Request.TotalBytes);
                fileName = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                if (fileData != null)
                {
                    fileName = fileData.FileName;
                    // 初始化byte长度.
                    file = new Byte[fileData.ContentLength];
                    // 转换为byte类型
                    Stream stream = fileData.InputStream;
                    stream.Read(file, 0, fileData.ContentLength);
                    stream.Close();
                }
            }
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                try
                {
                    if (fileName.LastIndexOf("\\") > 0)
                    {
                        fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                    }
                    string currentTime = DateTime.Now.ToString("yyyyMMddhhmmss");//
                    Random r = new Random(DateTime.Now.Millisecond);//生成随机数
                    int rndKey = r.Next(100000, 999999);
                    result = Path.GetFileName(fileName);   //获得文件名，返回后进行显示
                    string saveFileName = string.Format("{0}_{1}", currentTime + rndKey.ToString(), fileName);//保存文件的名称，如:20120615095819148931_Name.jpg
                    string saveFolder = Request.MapPath(string.Format("~{0}", folder));//保存的文件夹
                    if (!Directory.Exists(saveFolder))//如果文件夹不存在则创建
                    {
                        Directory.CreateDirectory(saveFolder);//创建文件夹
                    }
                    FileStream fs = new FileStream(Server.MapPath("~/" + string.Format("{0}/{1}", folder, saveFileName)), FileMode.Create, FileAccess.Write);
                    fs.Write(file, 0, file.Length);
                    fs.Flush();
                    fs.Close();
                    result = string.Format("{0}/{1}", folder, saveFileName);//返回结果
                }
                catch (Exception ex) { errMsg = ex.Message; }
            }
            var data = new { err = errMsg, msg = result };
            return this.Content(new JavaScriptSerializer().Serialize(data));//注意这里不能用Json方法,根据官方说明
        }
    }
}
